package model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;

import persistence.ContactGroupDAO;
import persistence.PersistenceUtil;


/**
 * 
 * @author hbriand
 * @class ContactGroup
 * @desc Describes a group of contacts (or category) and manages contacts
 */
@SuppressWarnings("serial")
@Entity
public class ContactGroup implements Serializable {

    @Id
    @GeneratedValue
    private Long id;
    private String name;
    @OneToMany(mappedBy = "group")
    private List<Contact> contactList;

    public ContactGroup() {
        this.contactList = new ArrayList<Contact>();
    }

    public ContactGroup(String name) {
        this.contactList = new ArrayList<Contact>();
        this.name = name;
        ContactGroupManager.getInstance().addGroup(this);
    }

    public void removeFromCGList() {
        ContactGroupManager.getInstance().deleteGroup(this);
    }

    public ArrayList<Contact> getContactList() {
        return (ArrayList<Contact>)this.contactList;
    }

    public void setContactList(ArrayList<Contact> contactList) {
        this.contactList = contactList;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void addContactToList(Contact contact) {
        this.contactList.add(contact);
    }

    // Returns the contact list of this group sorted in alphabetic order
    // Persistence methods needed to avoid LasyInitializationExceptions
    public List<Contact> getSortedContactList() {
    	EntityManager em = PersistenceUtil.getEM();
    	ContactGroupDAO cgDAO = new ContactGroupDAO();
    	ContactGroup newCG = cgDAO.merge(this);
        Arrays.sort(newCG.contactList.toArray());
        cgDAO.close();
        return this.contactList;
    }

    public boolean hasContact(Contact c) {
        return this.contactList.contains(c);
    }

    public void deleteContact(Contact selected) {
        this.contactList.remove(selected);
    }

    public boolean hasContactByFullName(String string) {
        try {
            this.getContactByFullName(string);
            return true;
        } catch (ContactNotFoundException e) {
            return false;
        }
    }

    public Contact getContactByFullName(String string) throws ContactNotFoundException {
        for (Contact c : this.contactList) {
            if (string.equals(c.fullName())) {
                return c;
            }
        }
        throw new ContactNotFoundException();
    }

    public void removeContact(Contact c) {
        if (this.hasContact(c)) {
            this.contactList.remove(c);
        }
    }
}
